var app = getApp(), u = app.require("utils/util.js"), a = app.require("utils/api.js"), o = app.require("utils/onfire.js"), h = app.require("utils/http.js"), n = app.require("utils/enums");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabs: ['商品', '详情', '评价'],
    currentTabsIndex: 0,
    autoplay:false,
    interval:5000,
    duration:1000,
    indicatorDots:false,
    imgUrls: ['/packages/images/5bfbad062c894.jpg','/packages/images/5bfbad0429929.jpg'],
    currentImgId:1,    
    flex:false,
    info:null,
    product:null,
    product_id:null,
    is_collect:0,//是否收藏
    couponPage:1,
    coupon_list:[],
    couponStatus:false,
    coupon_title:'',
    buyCount:1,
    addType:null,
    userInfo:null,
    commentTab:[],
    commentData: [],
    evaluaList:[],
    evaluaPage:1,
    cartCount:0,
    shoppingDirectory:'暂无购买规则',
    similarData:[],//同类商品
    scrollTop:0,
    type:'ALL'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.product_id = options.id;
    this.data.userInfo = wx.getStorageSync('userInfo');    
    this.getProductInfo(), 
    this.getShoppingDirectory(), 
    this.getCartList(), 
    this.getEvaluaList('ALL');
  },
  // 获取商品相关信息
  getProductInfo:function(){
    var t = this;
    var data = { store_id: a.storeId, uid: t.data.userInfo.uid, id: t.data.product_id }
    h.noLoadReq(a.getProductInfo, data, 'POST',function (res) {
      if(res.code == 0){        
        t.setData({
          info:res.data,
          product: res.data.product,
          product_id: res.data.product.product_id,
          is_collect: res.data.product.is_collect,
          // coupon_list: res.data.a_c_g_arr.coupon_list,
          couponStatus: res.data.a_c_g_arr.coupon,
          coupon_title: res.data.a_c_g_arr.coupon_title,
          couponShow: res.data.a_c_g_arr.coupon_list,
          similarData:res.data.similar,
          commentData:res.data.comment_data
        });
        t.getCommentTabs(res.data.comment_data),t.getCouponListById();
      }
    });
  },
  // 收藏、取消收藏商品
  collect: function (e){
    var t = this;
    var product_id = e.currentTarget.dataset.id;
    var data = { store_id: a.storeId, uid: t.data.userInfo.uid, product_id: t.data.product_id, types:1}
    h.noLoadReq(a.addOrCancelCollect, data, 'POST', function (res) {
      if(res.code == 0){        
        if (t.data.is_collect == 0){
          u.toast('收藏成功');
          t.setData({ is_collect: 1 });
        }else{
          u.toast('取消收藏成功');
          t.setData({ is_collect: 0 });
        }
      }
    });
  },
  // 获取优惠券列表
  getCouponListById:function(){
    var t = this;
    var data = { 
      store_id: a.storeId,
      page: t.data.couponPage,
      product_id: t.data.product_id,
    }
    h.noLoadReq(a.getConponList, data, 'POST', function (res) {
      if (res.code == 0) {
        t.setData({
          coupon_list: res.data.coupon_list
        });
      }
    });
  },
  // 获取购买规则
  getShoppingDirectory:function(){
    var t = this;
    var data = { 
      product_id: t.data.product_id 
    }
    h.noLoadReq(a.shoppingDirectory, data, 'POST', function (res) {
      if (res.code == 0) {
        t.setData({
          shoppingDirectory: u.filterHTMLTag(res.data.info)
        });
      }
    });
  },
  // 获取评价类型列表
  getCommentTabs: function (commentData){
    var commentTab = [];
    for(var index in commentData){
      var add = null;
      switch(index){
        case 'total':
          add = { name: '全部', type: 'ALL', count: commentData[index]};
          commentTab[0] = add;
          break;
        case 't1':
          add = { name: '差评', type: 'CHA', count: commentData[index] };
          commentTab[3] = add;
          break;
        case 't2':
          add = { name: '中评', type: 'ZHONG', count: commentData[index] };
          commentTab[2] = add;
          break;
        case 't3':
          add = { name: '好评', type: 'HAO', count: commentData[index] };
          commentTab[1] = add;
          break; 
      }
    }
    console.log(commentTab);
    this.setData({ commentTab: commentTab });
  },
  // 点击查看全部评价
  seeEvaluateAll:function(){
    this.getEvaluaList('ALL'), this.goTop(),   
    this.setData({ currentTabsIndex:2});
  },
  // 获取评价数据
  getEvaluaList:function(type){
    var t = this;
    var data = { tab: type, page: t.data.evaluaPage, product_id: t.data.product_id }
    h.postReq(a.getEvaluateList, data, function (res) {
      if (res.code == 0) {
        t.setData({
          evaluaList: t.data.evaluaList.concat(res.data.comment_list),
          evaluaPage: t.data.evaluaPage+1
        });
      }
    });
  },
  // 顶部tab切换
  switchTabs:function(e){
    var index = e.currentTarget.dataset.index;
    // index == 2 ? this.getEvaluaList() : '';
    this.goTop(),this.setData({
      currentTabsIndex:index
    });
  },
  // 回到页面顶部
  goTop:function(){
    if (wx.pageScrollTo && this.data.scrollTop > 0) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    }   
  },

  // 商品图片切换
  swiperChange:function(e){
    console.log(e);
    var current = e.detail.current;
    this.setData({ currentImgId: (current + 1)});
  },
  // 显示购买规则弹窗
  showBuyRules:function(e){
    let popupComponent = this.selectComponent('.Popup_A');
    popupComponent && popupComponent.show();
    this.setData({ flex: true });
  },
  // 关闭购买规则弹窗
  closeBuyRules:function(){
    let popupComponent = this.selectComponent('.Popup_A');
    popupComponent && popupComponent.hide(); 
    this.setData({ flex: false });   
  },
  // 显示购买药品弹窗
  showBuyProduct:function(e){
    let popupComponent = this.selectComponent('.Popup_B');
    popupComponent && popupComponent.show();
    var type = e.currentTarget.dataset.type;
    if (type == 'cart'){
      this.setData({ flex: true ,addType: type});
    }else{
      this.setData({ flex: true ,addType: type});
    }    
  },
  // 关闭购买药品弹窗
  closeBuyProduct:function(){
    let popupComponent = this.selectComponent('.Popup_B');
    popupComponent && popupComponent.hide();
    this.setData({ flex: false }); 
  },
  // 购买药品
  BuyProduct:function(){
    var t = this;
    let popupComponent = this.selectComponent('.Popup_B');    
    var data = { 
      store_id: a.storeId, uid: t.data.userInfo.uid, product_id: t.data.product_id, quantity: t.data.buyCount
    };
    if (t.data.addType == 'cart'){ 
      // 加入购物车流程     
      h.noLoadReq(a.addCart, data, 'POST' ,function (res) {
        if(res.code == 0){
          t.getCartList();
          u.success('成功加入购物车');
          popupComponent && popupComponent.hide(); 
          t.setData({ flex: false });   
        }else {
          u.toast(res.message);
        }                
      });      
    }else {
      // 直接购买流程
      h.postReq(a.buyNow, data, function (res) {
        if (res.code == 0) {
          popupComponent && popupComponent.hide();
          t.setData({ flex: false });
          var order_no = res.data.order_no;
          wx.navigateTo({
            url: '/pages/order/pay/index?order_no=' + order_no,
          })     
        } else {
          u.toast(res.message);
        }
      });      

    }  
  },
  // 问医生
  consultDoctor:function(e){
    var t = this;
    var em_id = e.currentTarget.dataset.em_id;
    var proJson = { em_id: em_id, pro_num:1};
    // console.log(proJson); return;
    var proString = escape(JSON.stringify(proJson));
    // console.log(proString);return;
    wx.navigateTo({
      url: "/template/prescribe/prescribe?url=https://tc2.zmmedical.cn/Patient/Index/quickIndex.htm&pro_string=" + proString
    });
  },
  // 显示领取优惠券弹窗
  showGetCoupon:function(){
    let popupComponent = this.selectComponent('.Popup_C');
    popupComponent && popupComponent.show();
    this.setData({ flex: true }); 
    // this.getCouponListById(); 
  },  
  // 领取优惠券
  receiveCoupon:function(e){
    var t = this;
    var data = {
      uid: t.data.userInfo.uid,
      coupon_id: e.currentTarget.dataset.coupon_id,      
    }
    h.noLoadReq(a.receiveCoupon, data, 'POST', function (res) {
      if (res.code == 0) {
        u.success('恭喜您抢到了！',function(){
          t.closeGetCoupon();
        });
      }
    });
  },
  // 关闭领取优惠券弹窗
  closeGetCoupon:function(){
    let popupComponent = this.selectComponent('.Popup_C');
    popupComponent && popupComponent.hide();
    this.setData({ flex: false }); 
  },
  // 跳转购物车页面
  goCart:function(){
    wx.switchTab({
      url: '/pages/cart/index/index',
    })
  },
  // 更新购物车数量部分
  minus: function (e) {
    var t = this;
    var index = parseInt(e.currentTarget.dataset.index);
    index -= 1;
    index < 0 ? index = 1 : index;
    t.setData({
      buyCount: index
    });    
  },
  plus: function (e) {
    var t = this;
    var index = parseInt(e.currentTarget.dataset.index); 
    index += 1;
    index > 99 ? index = 99 : index;
    t.setData({
      buyCount: index
    });     
  },
  inputChange: function (e) {},
  blurInput:function(e){
    var t = this;
    var value = e.detail.value;
    if (value <= 0){
      value = 1;
    }
    if(value > 99){
      value = 99;
    }
    console.log(value);
    t.setData({
      buyCount: value
    }); 
  },
  // 更新购物车数量部分

  // 获取购物车的所选商品
  getCartList:function(){
    var t = this;
    var data = {
      store_id: a.storeId,
      uid: t.data.userInfo.uid
    };
    h.noLoadReq(a.getCartList, data, 'POST' ,function (res) {
      if (res.code == 0) {
        var cart_list = res.data.cart_list;
        for (var i = 0; i < cart_list.length; i++) {
          cart_list[i]['checked'] = true;
        }
        t.imputedCount(cart_list);
      }
    });
  },
  // 统计购物车所有商品的总数量 
  imputedCount: function (data){
    var t = this;
    var cartCount = 0;
    for (var i = 0; i < data.length; i++) {
      if (data[i].checked) {
        cartCount += data[i].pro_num;
      }
    }
    t.setData({
      cartCount: cartCount
    });
  },
  // 商品详情
  proudctInfo: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: 'info?id=' + id
    })
  },

  // 切换评价类型
  Selected:function(e){
    console.log(e);
    var type = e.currentTarget.dataset.type; 
    this.data.evaluaList = [];
    this.data.evaluaPage = 1;
    this.getEvaluaList(type);
    this.setData({ type: type, evaluaList: this.data.evaluaList, evaluaPage: this.data.evaluaPage});
  },
  /**
    * 生命周期函数--监听页面加载
    */
  onPageScroll: function (event) {
    var scrollTop = event.scrollTop;
    this.setData({ scrollTop: scrollTop});
  },
  /**
  * 页面上拉触底事件的处理函数
  */
  onReachBottom: function () {
    if (this.data.currentTabsIndex == 2){
      this.getEvaluaList(this.data.type);
    }
  },
})